from src.config.agents import AGENT_LLM_MAP
from src.llms.llm import get_llm_by_type
from src.supabase_db.supabase import DBConnection
from langchain_core.messages import HumanMessage, SystemMessage
import logging
logger = logging.getLogger(__name__)

async def generate_project_name(user_id:str, thread_id: str, prompt: str, agent_code: str):
    """重命名并插入项目到数据库"""

    logger.info(f"启动后台任务以生成项目名称: {thread_id}")
    try:
        db_conn = DBConnection()
        client = await db_conn.client

        existing = await client.table("projects").select("*").eq("user_id", user_id).eq("project_id", thread_id).execute()

        if existing.data:
            return existing.data[0]

        model_name = "openai/gpt-4o-mini"
        system_prompt = "你是一个有用的助手，根据用户的消息为聊天线程生成极其简洁的标题（最多2-4个单词）。回复时只用标题，不要用其他文字或标点符号。"
        user_message = f"生成一个极其简短的标题（只有2-10个字），以这条消息开始一个聊天线程: \"{prompt}\""
        messages = [SystemMessage(content=system_prompt), HumanMessage(content=user_message)]

        logger.debug(f"Calling LLM ({model_name}) for project {thread_id} naming.")

        response = get_llm_by_type(AGENT_LLM_MAP["default"]).invoke(messages)

        generated_name = response.content
        if generated_name:
            cleaned_name = generated_name.strip('\'" \n\t')
            if cleaned_name:
                generated_name = cleaned_name
                logger.info(f"LLM generated name for project {thread_id}: '{generated_name}'")
            else:
                logger.warning(f"LLM returned an empty name for project {thread_id}.")
        else:
            logger.warning(f"Failed to get valid response from LLM for project {thread_id} naming. Response: {response}")

        if generated_name:
            update_result = await client.table('projects').insert({"user_id": user_id, "project_id": thread_id,"name": generated_name, "agent_code": agent_code}).execute()
            if hasattr(update_result, 'data') and update_result.data:
                logger.info(f"Successfully updated project {thread_id} name to '{generated_name}'")
                return update_result.data[0]
            else:
                logger.error(f"Failed to update project {thread_id} name in database. Update result: {update_result}")
        else:
            logger.warning(f"No generated name, skipping database update for project {thread_id}.")

    except Exception as e:
        logger.error(f"Error in background naming task for project {thread_id}: {str(e)}")
    finally:
        # No need to disconnect DBConnection singleton instance here
        logger.info(f"Finished background naming task for project: {thread_id}")


async def get_project_list(user_id: str):
    """获取用户项目列表"""
    db_conn = DBConnection()
    client = await db_conn.client
    result = await client.table('projects').select('*').eq('user_id', user_id).order("created_at", desc=True).range(0, 29).execute()
    return result.data